<?php

/**
 * 短网址生成类
 */
class Url {

    private $dict = array(0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', 4 => 'e', 5 => 'f', 6 => 'g', 7 => 'h', 8 => 'i', 9 => 'j', 10 => 'k', 11 => 'l', 12 => 'm', 13 => 'n', 14 => 'o', 15 => 'p', 16 => 'q', 17 => 'r', 18 => 's', 19 => 't', 20 => 'u', 21 => 'v', 22 => 'w', 23 => 'x', 24 => 'y', 25 =>
        'z', 26             => '0', 27 => '1', 28 => '2', 29 => '3', 30 => '4', 31 => '5', 32 => '6', 33 => '7', 34 => '8', 35 => '9', 36 => 'A', 37 => 'B', 38 => 'C', 39 => 'D', 40 => 'E', 41 => 'F', 42 => 'G', 43 => 'H', 44 => 'I', 45 => 'J', 46 => 'K', 47 => 'L', 48 => 'M', 49 => 'N', 50 => 'O', 51 => 'P', 52 => 'Q', 53 => 'R', 54 => 'S', 55 => 'T', 56 => 'U', 57 => 'V', 58 => 'W', 59 => 'X', 60 => 'Y', 61 => 'Z');

    private $manger = null;

    public function __construct() {
        $this->manger = new MongoDB\Driver\Manager("mongodb://127.0.0.1:27017/urldb");
    }

    // 给定一个10进制数值，转化为62为进制
    private function getDec62($idnum) {
        $to = 62;
        $ret = '';
        do {
            $ret = $this->dict[bcmod($idnum, $to)] . $ret;
            $idnum = bcdiv($idnum, $to);
        } while ($idnum > 0);
        return $ret;
    }

    // 查询
    private function find($filter,$options){
        $query = new MongoDB\Driver\Query($filter,$options);
        $cursor = $this->manger->executeQuery('urldb.url',$query);
        $ret = $cursor->toArray();
        return $ret;
    }
    // 获取自动增长ID
    private function getNum(){
        $cmd['findAndModify'] = 'cnt1';
        $cmd['query'] = ['_id'=>1];
        $cmd['update'] = ['$inc'=>['seq'=>1]];

        $cmdobj = new MongoDB\Driver\Command($cmd);
        $cursor = $this->manger->executeCommand('urldb',$cmdobj);
        $response = $cursor->toArray()[0];
        $seq = $response->value->seq;
        return intval($seq);
    }

    // 根据源URL得到Sn
    public function getSn($ori) {
        $filter = ['url' => $ori];
        $options = [
            'limit' => 1
        ];
        $ret = $this->find($filter,$options);
        if (count($ret) == 0) {
            return false;
        } else {
            return $ret[0]->sn;
        }
    }

    // 根据sn获取url地址
    public function getUrl($sn) {
        $filter = ['sn' => $sn];
        $options = ['limit' => 1];
        $ret = $this->find($filter,$options);
        if (count($ret) == 0) {
            return false;
        } else {
            return $ret[0]->url;
        }
    }

    // 添加源URL地址并返回对应短地址
    public function addShortUrl($oriurl) {
        $sn = $this->getSn($oriurl);
        if($sn){
            return $sn;
        }
        $seq = $this->getNum();
        $sn = $this->getDec62($seq);
        $bulk = new MongoDB\Driver\BulkWrite(['ordered' => true]);
        $bulk->insert(['_id'=>$seq,'sn'=>$sn,'url'=>$oriurl]);
        $result = $this->manger->executeBulkWrite('urldb.url',$bulk);
        return $sn;
    }

}